// 服务器状态检查工具
const { get } = require("./request.js");

/**
 * 检查服务器状态
 */
async function checkServerStatus() {
  try {
    const result = await get("/banners", {}, { showLoading: false });
    return {
      status: "online",
      message: "服务器运行正常",
      data: result,
    };
  } catch (error) {
    if (error.errMsg && error.errMsg.includes("ERR_CONNECTION_REFUSED")) {
      return {
        status: "offline",
        message: "服务器未启动，请检查后端服务",
        error: error,
      };
    } else if (error.errMsg && error.errMsg.includes("timeout")) {
      return {
        status: "timeout",
        message: "服务器响应超时",
        error: error,
      };
    } else {
      return {
        status: "error",
        message: "服务器连接异常",
        error: error,
      };
    }
  }
}

/**
 * 显示服务器状态
 */
async function showServerStatus() {
  const status = await checkServerStatus();

  let title = "服务器状态";
  let content = status.message;

  if (status.status === "offline") {
    title = "⚠️ 服务器离线";
    content =
      "后端服务器未启动，请检查服务器状态。\n\n解决方案：\n1. 检查后端服务器是否运行\n2. 确认端口8080未被占用\n3. 检查网络连接";
  } else if (status.status === "timeout") {
    title = "⏰ 服务器超时";
    content = "服务器响应超时，请检查网络连接。";
  } else if (status.status === "error") {
    title = "❌ 连接错误";
    content = "服务器连接异常，请检查配置。";
  } else {
    title = "✅ 服务器正常";
    content = "服务器运行正常，所有功能可用。";
  }

  wx.showModal({
    title: title,
    content: content,
    showCancel: false,
    confirmText: "确定",
  });

  return status;
}

module.exports = {
  checkServerStatus,
  showServerStatus,
};
